<script setup>
import { ref } from 'vue';
import { doPost } from '../http/httpRequest';
import { showMessage } from '../util/message';
import { TOKEN_NAME } from '../util/constant.js'

//定义2个对象
 let user = ref({})
 let userFormRef = ref()

 //编写校验规则
 let userRules = {
  // 账号校验规则
  loginAct: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 10, message: '长度需要在2到10之间', trigger: 'blur' },
  ],
  // 密码校验规则
  loginPwd: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 12, message: '长度需要在6到12之间', trigger: 'blur' },
  ],
 }


//定义登录函数
const login = (formEl) => {

  if(!formEl){
    //判断formEl是否有值
    return
  }
  //校验
  formEl.validate(valid => {
    //若valid是true则校验通过
    if(valid){
      //获取表单参数利用axios传给后端
      let loginAct = user.value.loginAct 
      let loginPwd = user.value.loginPwd

      //创建JavaScript的FormData对象
      let formData = new FormData()
      formData.append('loginAct', loginAct)
      formData.append('loginPwd', loginPwd)

      //利用axios发送请求
      doPost('/api/login',formData).then(res =>{

        if(res.data.code == 200){
          //存储token  
          //关闭浏览器之后token还存在
          localStorage.setItem(TOKEN_NAME,res.data.info)

          //关闭浏览器之后token就没有了
          //sessionStorage.setItem('loginToken',res.data.info)

          //路由到dashboard
          window.location.href = '/dashboard'
          
        }else{
          showMessage(res.data.msg,'error')
        }
      })
    }
  })

}

</script>

<template>
  <el-container>
    <!--左侧--> <!--运行后：<aside class="el-aside" style="--el-aside-width: 200px;"> Aside </aside> -->
    <el-aside width="200px">
      <img class="loginImg" src="../assets/login.png">
      <div class="loginTitle">欢迎使用动力云客系统</div>
    </el-aside>

    <!--右侧-->
    <el-main>
      <div class="welcome">欢迎登录</div>
     
      <el-form label-width="55px" style="width: 60%; margin: auto;" 
        :model="user"
        :rules="userRules"
        ref="userFormRef"
      >
        <el-form-item label="账号" prop="loginAct">
          <el-input v-model="user.loginAct" />
        </el-form-item>
        <el-form-item label="密码" prop="loginPwd">
          <el-input type="password" v-model="user.loginPwd" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="login(userFormRef)">登 录</el-button>
        </el-form-item>
      </el-form>
    </el-main>
  </el-container>
</template>

<style scoped>
.el-aside {
  background: #1a1a1a;
  height: calc(100vh);
  width: 40%;
  text-align: center;
}
.loginImg {
  margin-top: 100px;
  margin-bottom: 50px;
  width: 500px;
}
.loginTitle {
  color: #f8f8f8;
  font-size: 28px;
}
.el-main {
  text-align: center;
  padding-top: 100px;
}
.welcome {
  margin-bottom: 30px;
  font-weight: bold;
}
.el-button {
  width: 100%;
}
</style>